package org.opens.config;

import org.opens.util.R;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author zym
 * @Date 2022/6/28 17:32
 */
@ControllerAdvice
@ResponseBody
public class MyControllerAdvice {

    /**
     * RuntimeException异常处理
     */
    @ExceptionHandler(RuntimeException.class)
    public R<String> handleMethodRuntimeException(RuntimeException ex, HttpServletRequest request) {
        return R.error(null, ex.getMessage());
    }

    /**
     * 接口参数验证异常处理
     * @param e 异常
     * @param request 请求体
     * @return 所有的接口验证结果
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<List<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> errMsgList = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
        return R.error(errMsgList);
    }

}
